package guigu.ChangeStream;

import org.junit.Test;

import java.io.*;

/**
 * 处理流之二：转换流的使用
 * 1. 转换流：属于字符流
 *    InputStreamReader:将一个字节的输入流转换为字符的输入流
 *    OutputStreamWriter:将一个字符的输出流转化为字节的输出流
 *
 * 2. 作用：提供字节流与字符流之间的转换
 *
 * 3. 解码：字节、字节数组 ---->字符数组、字符串
 *    编码：字符数组、字符串 ----->字节、字节数组
 */
public class InputStreamReaderTest {
    /*
    InputStreamReader使用：实现字节的输入流到字符的输入流的转换
     */
    @Test
    public void test1()
    {
        InputStreamReader isr = null;
        try {
            FileInputStream fis = new FileInputStream("dbcp.txt");
            //InputStreamReader isr = new InputStreamReader(fis);//使用系统默认的字符集
            //参数2指明了字符集
            isr = new InputStreamReader(fis,"UTF-8");
            char cubf[] = new char[20];
            int len;
            while ((len=isr.read(cubf))!=-1)
            {
                String str = new String(cubf,0,len);
                System.out.println(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(isr!=null)
            {
                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /*
    综合使用InputStreamReader和OutputStreamWriter
     */
    @Test
    public void test2()
    {
        InputStreamReader isr = null;//用UTF-8解码
        OutputStreamWriter osw = null;//用gbk编码
        try {
            File srcFile = new File("dbcp.txt");
            File destFile = new File("dbcp_gbk.txt");

            FileInputStream fis = new FileInputStream(srcFile);
            FileOutputStream fos = new FileOutputStream(destFile);

            isr = new InputStreamReader(fis);
            osw = new OutputStreamWriter(fos,"gbk");

            char cubf[] = new char[20];
            int len;
            while ((len=isr.read(cubf))!=-1)
            {
                osw.write(cubf,0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(osw!=null)
            {
                try {
                    osw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(isr!=null)
            {
                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
